package com.example.demo.module.user.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.entity.response.ResCode;
import com.example.demo.common.entity.response.Rs;
import com.example.demo.common.annotation.SkipToken;
import com.example.demo.constant.Constant;
import com.example.demo.entity.pojo.user.UserPoJo;
import com.example.demo.entity.request.user.UserRequest;
import com.example.demo.entity.response.user.UserResponse;
import com.example.demo.module.user.service.UserService;
import com.example.demo.utils.ExcelUtil;
import com.example.demo.utils.JwtUtil;
import com.example.demo.validator.UserValidator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * .
 *
 * @author Li Zhiyuan
 * @since 2020/8/21
 */

@RestController("musllerc")
@RequestMapping("/user")
@Api(tags = "用户接口")
@Slf4j
public class UserController {
    @Resource
    private UserService service;
    @Resource
    private UserValidator validator;

    @InitBinder
    void initBinder(WebDataBinder binder) {
        binder.addValidators(validator);
    }

    @PostMapping
    @ApiOperation(value = "注册")
    @SkipToken
    public ResponseEntity<Rs<UserResponse>> register(@Valid @RequestBody UserRequest request) {
        long id = service.create(request.getName(), request.getPassword());
        return Rs.ok(Rs.json().put("id", id));

    }

    @PostMapping(path = "/login")
    @ApiOperation(value = "登录", notes = "根据用户名和密码登录，返回token")
    @SkipToken
    public ResponseEntity<Rs<Object>> login(HttpServletRequest request,
                                            @RequestParam(value = "name") String userName,
                                            @RequestParam(value = "password") String passWord
    ) {
        String msg = "用户不存在";
        UserPoJo user1 = new UserPoJo();
        user1.setName(userName);
        UserPoJo user = service.selectOne(user1);
        if (user != null) {
            if (user.getPassword().equals(passWord)) {
                msg = "登录成功";
                String token = JwtUtil.generateToken(user, 1);
                return Rs.ok(Rs.json().put("msg", msg).put("user", user).put("Authorization", token));

            } else {
                return Rs.fail(ResCode.COMPANY_PASSWORD_ERROR);
            }
        }
        return Rs.fail(msg);
    }

    @GetMapping(path = "/all")
    @ApiOperation(value = "获取用户列表")
    public ResponseEntity<Rs<Page<UserPoJo>>> page(
            @ApiParam("查询条件 用户名称") @RequestParam(value = "keywords", required = false) final String keywords,
            @ApiParam("页号,从1开始")
            @RequestParam(value = "page", required = false, defaultValue = "1") final int page,
            @RequestParam(value = "size", required = false, defaultValue = "10") final int size) {
        Page<UserPoJo> pageList = service.page(keywords, page, size);
        return Rs.ok(pageList);
    }

    @PostMapping(path = "/download")
    @ApiOperation(value = "导出数据", produces = "application/octet-stream")
    public void download(HttpServletResponse response,
                         @ApiParam(value = "文件名", example = "供应商台账") @RequestParam("fileName") String fileName) throws IOException {
        List list = service.selectAll();
        ExcelUtil.writeWithHead(response, list, fileName, UserPoJo.class);
    }


    @PostMapping("/upload")
    @ApiOperation(value = "导入数据")
    public void upload(@ApiParam(value = "文件", example = "供应商台账.xlsx") @RequestParam MultipartFile file) throws Exception {
        log.info("导入数据");
        ExcelUtil.readWithHead(file, service, UserPoJo.class);
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "更新用户")
    public ResponseEntity<Rs<Object>> upload(@PathVariable("id") final long id, @RequestParam("name") String name) {

        LambdaUpdateWrapper<UserPoJo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserPoJo::getId, id);
        wrapper.set(UserPoJo::getName, name);
        //不会自动填充update_time
        service.update(wrapper);
        //会自动填充update_time
        service.update(new UserPoJo(), wrapper);

        UserPoJo poJo = service.getById(id);
        poJo.setName(name);
        service.updateById(poJo);


        return Rs.ok(ResCode.API_SUCCESS_EXEC_UPDATE);
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户")
    public ResponseEntity<Rs<Object>> delete(@PathVariable("id") final long id, @ApiIgnore @RequestParam(Constant.HeaderKey.COMPANY_ID) long companyId) {
        log.info("delete:[id:{}, companyId:{}]", id, companyId);
        service.remove(Wrappers.<UserPoJo>lambdaQuery().eq(UserPoJo::getCompanyId, companyId).eq(UserPoJo::getId, id));
        return Rs.ok(ResCode.API_SUCCESS_EXEC_DELETE);
    }
}
